//
//  UserAccountViewModel.swift
//  weibo09
//
//  Created by Jet on 16/5/8.
//  Copyright © 2016年 Jet. All rights reserved.
//

import UIKit
import AFNetworking

//封装网络请求的方法
class UserAccountViewModel: NSObject {
    
    var account:UserAccountInfoModel?
    //记录用户登录状态
    var userLogin: Bool{
        return account?.access_token != nil
    }
    

    var token:String?{
        
        return account?.access_token
    }

    
    //初始化赋值
    override init() {
        account = UserAccountInfoModel.loadAccount()
    }

    func loadAccessToken(code:String,finshed:(error:NSError?)->()){
        
        let AFN = AFHTTPSessionManager()
        //因为AFN无法识别text/plain格式的数据，所以需要插入text/plain
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        //请求url官方提供
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        //请求参数
        let parameters = ["client_id":client_id,"client_secret":appSecret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
        
        AFN.POST(urlString, parameters: parameters, success: { (_, result) in
            
            if let dict = result as?[String:AnyObject] {
                
                let account = UserAccountInfoModel(dict: dict)
                self.loadUserInfo(account, finshed: finshed)
            }
            
        }) { (_, error) in
            
            print("error:\(error)")
        }
        
    }
    
    //加载用户信息
    func loadUserInfo(account:UserAccountInfoModel,finshed:(error:NSError?)->()){
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        let AFN = AFHTTPSessionManager()
        let parameters = ["access_token":account.access_token!,"uid":account.uid!]
        
        AFN.GET(urlString, parameters: parameters, success: { (_, result) in
            print(result)
            
            if let dict = result as?[String:AnyObject]{
                
                account.name = dict["name"] as?String
                account.avatar_large = dict["avatar_large"]as?String
                account.saveAccount()
                finshed(error: nil)
            }
        }) { (_, error) in
            finshed(error: error)
        }
    }

}
